package com.lean.android.sysinfo

import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.BatteryManager
import kotlin.math.roundToLong

object BatteryStatusProvider {

    private fun Double.round2(): Double = try {
        (this * 100.0).roundToLong() / 100.0
    } catch (e: Exception) {
        this
    }

    private fun getBatteryStatusIntent(context: Context): Intent? {
        val filter = IntentFilter(Intent.ACTION_BATTERY_CHANGED)
        return context.registerReceiver(null, filter)
    }

    fun getBatteryStatus(context: Context): BatteryStatus {
        val intent = getBatteryStatusIntent(context) ?: return BatteryStatus()
        val status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1)
        val isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING || status == BatteryManager.BATTERY_STATUS_FULL
        val chargingType = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1)

        // Level
        val level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1)
        val scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1)
        var percentage = 0.0
        if(level != -1 && scale != -1){
            percentage = (level / scale.toFloat() * 100.0).round2()
        }

        return BatteryStatus(
            isCharging,
            chargingType,
            percentage
        )
    }

    data class BatteryStatus(
        val isCharging: Boolean = false,
        val chargingType: Int = -1,
        val levelPercentage: Double = 0.0
    )

}